import { useHistory } from 'react-router-dom';
import { useState, useEffect } from 'react';

import { message, Empty } from 'antd';

import DragApi from '@/pages/Drag/service';
import Loading from '@/pages/Drag/sub-components/previewModal/Loading';
import PreviewForm from '@/pages/Drag/sub-components/previewModal/previewForm';
import checkFormValidator from '@/pages/Drag/sub-components/previewModal/checkFormValidator';
import styles from './index.less';

function PreviewFormBox() {
  const history: any = useHistory();
  const [showLoading, setLoding] = useState(false);
  const [formData, setFormData] = useState<any>([]);
  const [rules, setRules] = useState<any>([]);
  const [formEvents, setFormEvents] = useState<any>();
  const [validators, setValidators] = useState<any>();
  const [title, setTitle] = useState('');

  useEffect(() => {
    getFormInfo();
  }, [0]);

  async function getFormInfo() {
    const { id } = history.location.query;
    if (!id) return;
    // console.log(id);
    setLoding(true);
    const res = await DragApi.info(id);
    console.log(res);
    const { infosData } = res.data;
    if (!infosData) return setLoding(false);
    const { layoutData, fieldShowRules, formEventObj, validators } = JSON.parse(infosData);
    // return console.log(fieldShowRules)
    // layoutData.forEach((v:any)=>{
    //   v.value = '';
    // })
    setFormData(layoutData);
    setFormEvents(formEventObj);
    setRules(fieldShowRules);
    setValidators(validators);
    setTitle(res.data.name);

    // getBackData(layoutData);

    setLoding(false);
  }

  async function submit(reqParams: any) {
    const checkForm = checkFormValidator(validators, formData);
    if (!checkForm) return;

    // reqParams.startDate = moment(reqParams.startDate).format("YYYY-MM-DD")
    // reqParams.endDate = moment(reqParams.endDate).format("YYYY-MM-DD")

    try {
      console.log('reqParams:', reqParams);
      // return
      setLoding(true);
      const res = await DragApi.startProcess(reqParams);

      console.log('submit', res);
      history.push('/approval');
      setLoding(false);
    } catch (err) {
      setLoding(false);
    }
  }

  function onSetFormData(data: any) {
    // console.log(data);
    setFormData([...data]);
  }

  return (
    <div className="previewForm" style={{ width: '100%' }}>
      {/* className={styles.previewForm} */}
      {formData.length > 0 ? (
        <>
          <h1 className="form-title">{title}</h1>
          <PreviewForm
            formData={formData}
            setFormData={onSetFormData}
            onPreviewFormSubmit={submit}
            rules={rules}
            formEvents={formEvents}
          />
        </>
      ) : (
        <Empty />
      )}

      {showLoading && <Loading />}
    </div>
  );
}

export default PreviewFormBox;
